import { Button, Card, Divider, Space, Tabs } from "antd";
import { message, Upload } from 'antd';
import type { UploadProps } from 'antd';
import { InboxOutlined } from '@ant-design/icons';
import { useState } from "react";
import styles from "./index.less";
import http from "@/http/axios_config";
import AppConstant from "@/services/common/AppConstant";

const { Dragger } = Upload;


const props: UploadProps = {
  name: 'file',
  multiple: true,
  maxCount: 1
};



export default function PdfTool() {
  const [fileList, setFileList] = useState<any[]>([])

  const handleConvert = async () => {
    const formData = new FormData();
    const file = fileList[0].originFileObj;
    formData.append('file', file);
    const resp = await http.post(AppConstant.UMI_BASE_URL + "/api/pdf-tool/pdf-to-image", formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
      responseType: 'blob'
    })
    const url = window.URL.createObjectURL(new Blob([resp.data]));
    const link = document.createElement('a');
    link.href = url;
    const filename = file.name.replace(".pdf", ".png")
    link.setAttribute('download', filename); // 设置下载文件的名称和扩展名
    document.body.appendChild(link);
    link.click();
    link.remove();
  }

  const PdfToImageView = <>
    <Dragger 
      {...props}
      fileList={fileList}
      onChange= {(info) => {
        const { status } = info.file;
        if (status !== 'uploading') {
        }
        if (status === 'done') {
          message.success(`${info.file.name} file uploaded successfully.`);
        } else if (status === 'error') {
          message.error(`${info.file.name} file upload failed.`);
        }
        setFileList([...info.fileList])
      }}
      beforeUpload={() => false}
      className={styles['pdf-upload']}
      height={400}
      style={{display: "flex", justifyContent: "center", alignItems: "center"}}
    >
      <p className="ant-upload-drag-icon">
        <InboxOutlined />
      </p>
      <p className="ant-upload-text">点击上传PDF文档 或 拖拽PDF文档至此，支持格式： .pdf,不支持超过10M的文件 </p>
    </Dragger>
    <Divider></Divider>
    <Space style={{display: 'flex', justifyContent: 'center', alignItems: 'center'}}>
      <Button type="primary" onClick={() => handleConvert()}>转换并下载</Button>
    </Space>
  </>

  const items: any[] = [
    {
      label: "PDF转图片",
      id: 1,
      children: PdfToImageView
    }
  ]

    return (<Card
      style={{minHeight: '80vh'}}
    >
        <Tabs
        tabPosition={'left'}
        items={items.map((item) => {
          return {
            label: item.label,
            key: item.id,
            children: item.children,
          };
        })}
      />
    </Card>)
}